﻿using System.IO;
using System.Net;

public partial class Runner
{

    void Download(PackageDef packageDef, string nupkgCacheFilePath)
    {
        cacheCleanRequired = true;
        using (var webClient = new WebClient())
        {
            webClient.Credentials = CredentialCache.DefaultNetworkCredentials;
            var address = string.Format("https://nuget.org/api/v2/package/{0}/{1}", packageDef.Id, packageDef.Version);
            string tempFileName = null;
            try
            {
                tempFileName = Path.GetTempFileName();
                WriteInfo("Downloading " + address);
                webClient.DownloadFile(address, tempFileName);
                File.Copy(tempFileName, nupkgCacheFilePath, true);
            }
            catch (WebException webException)
            {
                if (tempFileName != null)
                {
                    File.Delete(tempFileName);
                }
                throw new ExpectedException(string.Format("Failed to download '{0}' due to '{1}'. This package may no longer exist on the nuget feed or there is a problem with your internet connection.", address, webException.Message));
            }
        }
    }

}